package com.sailorj.itools.generate;

import com.sailorj.itools.constants.ParserMapConstants;
import com.sailorj.itools.entity.ParserColumn;
import com.sailorj.itools.entity.ParserTable;
import com.sailorj.itools.utils.CamelCaseUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DDLParser {
    public static void main(String[] args) {
        String sql = "CREATE TABLE `store_info`  (\n" +
                "  `id` int(0) NOT NULL AUTO_INCREMENT,\n" +
                "  `store_no` int(0) NOT NULL DEFAULT 0 COMMENT '店别',\n" +
                "  `area_no` int(0) NOT NULL DEFAULT 0 COMMENT '区域(1.华东;2.华北;3.东北;4.华中;5.华南)',\n" +
                "  `admin_code` int(0) NULL DEFAULT 0 COMMENT '区域代码',\n" +
                "  `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '店名',\n" +
                "  `full_name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '全名',\n" +
                "  `gui_name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '注册名称',\n" +
                "  `status` int(0) NULL DEFAULT 0 COMMENT '状态',\n" +
                "  `address` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '营业地址',\n" +
                "  `phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话',\n" +
                "  `province` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '省',\n" +
                "  `county` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '市/州',\n" +
                "  `begin_time` datetime(0) NULL DEFAULT NULL COMMENT '营业开始时间',\n" +
                "  `end_time` datetime(0) NULL DEFAULT NULL COMMENT '营业结束时间',\n" +
                "  `location` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '坐标(x,y)',\n" +
                "  `created_date` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',\n" +
                "  `changed_date` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '异动时间',\n" +
                "  `linkman` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '联系人',\n" +
                "  `link_ding` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '负责DingId',\n" +
                "  `wx_ct_code` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '企业微信二维码',\n" +
                "  `wx_group_code` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '微信群聊二维码',\n" +
                "  PRIMARY KEY (`id`) USING BTREE\n" +
                ") ENGINE = InnoDB AUTO_INCREMENT = 111 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;";

        ParserTable parserTable = parseSql(sql);
        getCreateTableInfo(parserTable);
    }

    public static ParserTable parseSql(String sql) {
        sql = sql.toLowerCase();
        ParserTable table = new ParserTable();
        try {
            // 第一个括号前面的单词
            String tableNameRegex = "\\b(\\w+)\\s*\\(";

            Pattern tableNamePattern = Pattern.compile(tableNameRegex);
            Matcher tableNameMatcher = tableNamePattern.matcher(sql);

            if (tableNameMatcher.find()) {
                String tableName = tableNameMatcher.group(0).replace("(", "").trim();
                table.setSqlTableName(tableName);
            }

            String[] lines = sql.split("\n");
            boolean last = false;
            List<ParserColumn> columnList = new ArrayList<>();
            for (int i = 1; i < lines.length; i++) {
                ParserColumn column = new ParserColumn();
                String line = lines[i].trim();
                System.out.println("第" + i + "行：" + line);
                if (line.startsWith("(")) {
                    continue;
                }
                // 使用正则表达式拆分字符串
                String[] words = line.split("\\s+");

                String isNull = "";
                String defaultValue = "";
                String comments = "";
                for (int j = 0; j < words.length; j++) {
                    if (words[j].toLowerCase().equalsIgnoreCase("null")) {
                        isNull = words[j - 1].toLowerCase().equals("not") ? "否" : "是";
                    } else if (words[j].toLowerCase().equalsIgnoreCase("default")) {
                        defaultValue = words[j + 1];
                    } else if (words[j].toLowerCase().equalsIgnoreCase("comment")) {
                        comments = words[j + 1].replaceAll("'", "").replaceAll("\\,", "");
                    }
                }
                System.out.println(isNull);
                System.out.println(defaultValue);
                System.out.println(comments);

                System.out.println(Arrays.toString(words));

                // sheetNo
                String columnName = words[0];
                // varchar(20)
                String columnTypes = words[1];
                // String
                String columnType = columnTypes.replaceAll("\\(.*?\\)", "").split("\\s+")[0];

                column.setSqlColumnName(columnName);
                column.setJdbcType(columnType.toUpperCase());
                column.setColumnTypes(columnTypes);
                column.setColumnType(ParserMapConstants.JDBC_TYPE_MAP.get(columnType.toUpperCase()));
                column.setIsNull(isNull);
                column.setDefaultValue(defaultValue);

                String regex = "comment\\s+'(.*?)'";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(line);

                if (matcher.find()) {
                    String comment = matcher.group(1);
                    if (last) {
                        table.setTableComment(comment);
                    } else {
                        column.setColumnComment(comment);
                        column.setIndex(i);
                        columnList.add(column);
                    }
                }
                if ("update_time".equals(columnName)) {
                    last = true;
                }
            }
            Collections.sort(columnList); // 使用Comparable接口的排序
            table.setColumnList(columnList);
            String tableName = CamelCaseUtils.camelCase(table.getSqlTableName());
            table.setTableName(capitalizedStr(tableName)); // 首字母大写
            table.setTableName2(tableName); // 首字母小写

            System.out.println(table.getTableName());
            System.out.println(table.getTableComment());
            camelCase(table.getColumnList());
            for (ParserColumn column : table.getColumnList()) {
                System.out.println(column.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 转为驼峰单词
     */
    private static void camelCase(List<ParserColumn> columnList) {
        for (ParserColumn parserColumn : columnList) {
            String originalString = parserColumn.getSqlColumnName();
            parserColumn.setColumnName(CamelCaseUtils.camelCase(originalString));
        }
    }

    /**
     * 首字母大写
     */
    private static String capitalizedStr(String str) {
        String firstChar = str.substring(0, 1).toUpperCase();
        String remainingChars = str.substring(1);
        return firstChar + remainingChars;
    }

    /**
     * 根据SQL语句获取表名和建表参数
     */
    public static String getCreateTableInfo(ParserTable parserTable) {
        String content = "";
        String tableName = "";
        /**** 开始生成 ****/
        if (!StringUtils.isAllBlank(parserTable.getTableComment())) {
            tableName = parserTable.getSqlTableName() + "(" + parserTable.getTableComment() + ")";
        }
        content += "\n";
        content += "\n - " + tableName;
        content += "\n";
        content += "\n|字段|类型|空|默认|注释|";
        content += "\n|:----    |:-------    |:--- |-- -|------      |";

        for (ParserColumn parserColumn : parserTable.getColumnList()) {
            /**** 开始生成 ****/
            String msg = "|" + parserColumn.getSqlColumnName() + "|" + parserColumn.getColumnTypes() + "|" +
                    parserColumn.getIsNull() + "|" + parserColumn.getDefaultValue() + "|" + parserColumn.getColumnComment();
            content += "\n" + msg;
        }
        System.out.println(content);
        return content;
    }

}

